<template>
  <ant-modal
    modalWidth="1000"
    modalHeight="600"
    :visible="open"
    :modal-title="title"
    :adjust-size="true"
    @cancel="cancel"
  >
    <a-row slot="content">
      <a-spin :spinning="loading">
      <a-col :span="24">
        <a-card :bordered="false" style="min-height:calc(100vh - 125px);">
          <select-user selectModel="multi" v-if="showSetUser" ref="selectUserRef" @callBack='saveSelectUser' @close="showSetUser = false"/>
          <advance-table
            :columns="roleUserColumns"
            :data-source="subList"
            :title="title"
            :loading="subLoading"
            rowKey="id"
            size="middle"
            tableKey="system-roleuser-SysRoleIndex-table"
            @refresh="getOrderInfo(orderId)"
            :format-conditions="true"
            :row-selection="{ selectedRowKeys: selectedSubRowKeys, onChange: onSelectSubChange}"
            :pagination="{
              current: querySubParam.pageNum,
              pageSize: querySubParam.pageSize,
              total: subTotal,
              showSizeChanger: true,
              showLessItems: true,
              showQuickJumper: true,
              showTotal: (subTotal, range) => `第 ${range[0]}-${range[1]} 条，总计 ${subTotal} 条`,
              onChange: changeSubSize,
              onShowSizeChange: onShowSizeSubChange,
            }">
            <div class="table-operations" slot="button">
              <!-- <a-input-search
                placeholder="请输入编码或名称"
                v-model="querySubParam.userNameOrName"
                style="width: 150px"
                @search="handleQueryRoleUser" /> -->
              <a-button
                type="primary"
                size="small"
                @click="handleAddUser"
                v-hasPermi="['biz:bizOrderInstaller:add']">
                <a-icon type="plus" />添加用户
              </a-button>
              <a-button
                type="danger"
                v-if="!subMultiple"
                @click="handleDeleteSub"
                v-hasPermi="['biz:bizOrderInstaller:remove']">
                <a-icon type="delete" />删除
              </a-button>
            </div>

            <span slot="status" slot-scope="{record}">
              <a-badge status="processing" :text=" statusFormat(record) " />
            </span>
            <span slot="installerType" slot-scope="{record}">
              <a-select
                placeholder="请选择派送类型"
                v-model="record.installerType"
                :getPopupContainer="
                  triggerNode => {
                    return triggerNode.parentNode || document.body
                  }
                "
                style="width: 100%"
                allow-clear
              >
                <a-select-option  value="1" :disabled="form.deliveryType == 1">派送</a-select-option>
                <a-select-option  value="2" :disabled="form.installType == 1">安装</a-select-option>
              </a-select>
            </span>
            <span slot="installDate" slot-scope="{record}">
              <a-date-picker
                v-model="record.installDate"
                valueFormat="YYYY-MM-DD"
                :show-today="true"
                placeholder="选择日期"
                style="width: 100%"
              />
            </span>

            <span slot="remark" slot-scope="{text, record}">
              <a-input v-model="record.remark" placeholder="请输入备注" />
            </span>

            <span slot="operation" slot-scope="{text, record,index}">
              <a @click.stop="deleteSub(record)" >
                删除
              </a>
            </span>
          </advance-table>
        </a-card>
      </a-col>
    </a-spin>
    </a-row>

    <template slot="footer">
      <a-button type="primary" @click="submit" :disabled="loading" v-hasPermi="['biz:bizOrderInstaller:add']">保存</a-button>
      <a-button  @click="cancel">
        关闭
      </a-button>
    </template>
  </ant-modal>
</template>
<script>
  import AdvanceTable from '@/components/pt/table/AdvanceTable'
  import SelectUser from './SelectUser'
  import AntModal from '@/components/pt/dialog/AntModal'
  import { listBizProcessUser,delBizProcessUser } from '@/api/biz/bizProcessUser'
  import { listBizOrderInstaller,addBizOrderInstaller } from '@/api/biz/bizOrderInstaller'
  export default {
    name: 'ProcessUser',
    components: {
      AdvanceTable,
      SelectUser,
      AntModal
    },
    data () {
      return {
        title:'',
        open:false,
        deptId:undefined,
        processId:undefined,
        showSetUser:false,
        installerType:'',//类型 1-配送  2-安装
        orderId:'',//父订单编号
        // 表格缓存的数据 - 用来点击取消时回显数据
        cacheData: [],
        deleteData: [], // 可编辑表格待删除数据，数据库已存在数据界面假删除，保存到该集合，最终请求数据库删除
        subList: [],
        selectedRowKeys: [],
        selectedSubRowKeys: [],
        selectedRows: [],
        selectedSubRows: [],
        form:{},
        selectedUser: '',
        // 高级搜索 展开/关闭
        advanced: false,
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        subMultiple: true,
        selectItem: {},
        ids: [],
        subIds: [], // 子表选择id集合
        loading: false,
        subLoading: false,
        total: 0,
        subTotal: 0,
        // 日期范围
        dateRange: [],
        labelCol: {
          span: 6
        },
        wrapperCol: {
          span: 18
        },
        queryParam: {
          pageNum: 1,
          pageSize: 10,
          roleName: undefined,
          roleKey: undefined,
          status: undefined
        },
        querySubParam: {
          pageNum: 1,
          pageSize: 10
        },
        addModalRefName: 'addModal', // 添加弹窗ref名称
        columns: [
          {
            title: this.installerType == 1 ? '配送师傅' : (this.installerType == 2 ? '安装师傅' : ''),
            dataIndex: 'installerUserName',
            ellipsis: true,
            scopedSlots: {
              customRender: 'roleNameSolt'
            }
          },
          {
            title: '类型',
            dataIndex: 'installerType',
            width: '150px',
            ellipsis: true,
            scopedSlots: {
              customRender: 'installerType'
            }
          },
          {
            title: '备注',
            dataIndex: 'remark',
            align: 'center',
            scopedSlots: {
              customRender: 'remark'
            }
          },
        ],
        roleUserColumns: [
          {
            title: '师傅',
            dataIndex: 'installerUserName',
            ellipsis: true,
            scopedSlots: {
              customRender: 'roleNameSolt'
            }
          },
          {
            title: '类型',
            dataIndex: 'installerType',
            width: '150px',
            ellipsis: true,
            scopedSlots: {
              customRender: 'installerType'
            }
          },
          {
            title: '时间',
            dataIndex: 'installDate',
            width: '150px',
            ellipsis: true,
            scopedSlots: {
              customRender: 'installDate'
            }
          },
          {
            title: '备注',
            dataIndex: 'remark',
            align: 'center',
            scopedSlots: {
              customRender: 'remark'
            }
          },
          {
            title: '操作',
            dataIndex: 'remar',
            align: 'center',
            scopedSlots: {
              customRender: 'operation'
            }
          },
        ]
      }
    },
    filters: {},
    created () {
    },
    computed: {},
    methods: {
      getUserList () {
        // 只有保存的数据才加载字表数据
        this.subLoading = true
        this.querySubParam.processId = this.processId
        listBizProcessUser(this.querySubParam).then(response => {
          this.subList = response.data.list
          this.subTotal = response.data.total
          this.subLoading = false
        })
        this.subIds = []
        this.selectedSubRowKeys = []
        this.subMultiple = true
      },
      /** 搜索按钮操作 */
      handleQuery () {
        this.queryParam.pageNum = 1
        this.getList()
      },
      handleQueryRoleUser () {
        this.querySubParam.pageNum = 1
        this.getUserList()
      },
      selectFirstRecord () {
        // 定位选中行到第一条数据
        if (this.list.length > 0) {
           this.selectItem = this.list[0]
        } else {
          // 移除子表数据
           this.subList = []
           this.subTotal = 0
        }
      },
      handleAddUser () {
        this.showSetUser = true
        this.$nextTick(() => (
          this.$refs.selectUserRef.showSelectUser(this.deptId)
        ))
      },
      onShowSizeChange (current, pageSize) {
        this.queryParam.pageSize = pageSize
        this.getList()
      },
      onShowSizeSubChange (current, pageSize) {
        this.querySubParam.pageSize = pageSize
        this.getUserList()
      },
      onSizeChange (current, size) {
        this.queryParam.pageNum = 1
        this.queryParam.pageSize = size
        this.getList()
      },
      changeSize (current, pageSize) {
        this.queryParam.pageNum = current
        this.queryParam.pageSize = pageSize
        this.getList()
      },
      changeSubSize (current, pageSize) {
        this.querySubParam.pageNum = current
        this.querySubParam.pageSize = pageSize
        this.getUserList()
      },
      onSelectChange (selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
        this.ids = this.selectedRows.map(item => item.id)
        this.single = selectedRowKeys.length !== 1
        this.multiple = !selectedRowKeys.length
      },
      onSelectSubChange (selectedSubRowKeys, selectedSubRows) {
        this.selectedSubRowKeys = selectedSubRowKeys
        this.selectedSubRows = selectedSubRows
        this.subIds = this.selectedSubRows.map(item => item.userId)
        this.subMultiple = !selectedSubRowKeys.length
      },
      handleDeleteSub (row) {
         var that = this
        const userIds = row.userId || this.subIds
        console.log('userIds :>> ', userIds);
        this.$confirm({
          title: '确认删除所选中数据?',
          onOk: ()=>{
            this.subList = this.subList.filter(v=>!userIds.includes(v.userId))
            console.log('this.subList :>> ', this.subList);
            that.onSelectSubChange([], [])
          },
          onCancel () {}
        })
      },
      deleteSub(item,index){
        this.$confirm({
          title: '确认删除所选中数据?',
          onOk: ()=>{
            this.subList.splice(index,1)
          },
          onCancel () {}
        })

      },
      handleSetUser(row) {
        this.open = true
        this.orderId = row.id
        this.form = row
        this.getOrderInfo(row.id)
      },
      getOrderInfo(orderId){
        console.log('666 :>> ', 666);
        let param ={
          orderId:orderId ,//订单id
        }
        listBizOrderInstaller(param).then(res=>{
          if(res.code == 200){
            this.subList = res.data.list
          }else{
            this.$message.error(res.msg)
          }
        })
      },
      cancel () {
        this.open = false
        this.$emit('close')
      },
      saveSelectUser(user) {
        let ids = user.ids;
        let idArr = ids.split(";");
        let names = user.names;
        let nameArr = names.split(";");
        let defaultUsers = this.subList.map(v=>v.userId)
        let type = ()=>{
          if(this.form.deliveryType == 2){
            return '1'
          }
          if(this.form.installType == 2){
            return '2'
          }
          return ''
        }
        idArr.forEach((id,index)=>{
          this.subList.push({userId:id,installerUserName:nameArr[index],orderId:this.orderId,installerType:type()})
        })
        console.log('this.subList :>> ', this.subList);
        this.showSetUser = false
      },
      submit(){
        let param ={
          bizOrderInstallers:this.subList.map(v=>(v.installerStatus = v.installerStatus || 0,v)),
          id:this.orderId
        }
        this.loading = true
        addBizOrderInstaller(param).then(res=>{
          
          this.loading = false
          if(res.code == 200){
            this.$message.success('保存成功')
            // this.getOrderInfo(this.orderId);
            this.open = false
            this.$emit('ok')
          }else{
            this.$message.error(res.msg)
          }
        })
      },
    }
  }
</script>
<style lang="less">
  .ant-table-row.row-selection {
    background-color: #F0F2F5;
  }
</style>
